<template>
  <div>
    <div class="flex-between">
      <el-form :inline="true" ref="form" label-width="120px">
        <el-form-item label="管理员账户名：">
          <el-input
            v-model.trim="adminName"
            placeholder="请输入管理员账户名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="getList()">搜索</el-button>
        </el-form-item>
      </el-form>
      <div class="rt">
        <el-button type="primary" @click="addUser()">新增管理员</el-button>
      </div>
    </div>
    <el-table
      ref="multipleTable"
      :data="tableData"
      style="width: 100%"
      border
      :header-cell-style="tableHeaderColor"
      :cell-style="tableCellStyle"
    >
      <el-table-column prop="username" label="管理员账户"> </el-table-column>
      <el-table-column label="账户级别">
        <template slot-scope="scope">{{
          adminTypeMap[scope.row.type]
        }}</template>
      </el-table-column>
      <el-table-column label="创建时间" width="200">
        <template slot-scope="scope">{{
          scope.row.createTime | formatDate
        }}</template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="text" @click="addUser(scope.row)"
            >修改密码</el-button
          >
          <el-popconfirm
            v-if="scope.row.type !== 0"
            title="确定删除吗？"
            @confirm="del(scope.row.id)"
            style="margin-left: 20px"
          >
            <el-button slot="reference" type="text">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-handler">
      <div></div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageIndex"
        :page-sizes="pageSizeArr"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <el-dialog
      :title="isEdit ? '修改密码' : '新增管理员'"
      :visible.sync="addVisible"
      width="35%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="addForm"
        :model="addForm"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="管理员账户：" prop="username">
          <span v-if="isEdit">{{ addForm.username }}</span>
          <el-input
            v-else
            v-model.trim="addForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input
            type="password"
            v-model.trim="addForm.password"
            autocomplete="off"
          ></el-input>
          <span class="warning">*至少6个字符，中英文不限</span>
        </el-form-item>
        <el-form-item label="确认密码：" prop="confirmPassword">
          <el-input
            type="password"
            v-model.trim="addForm.confirmPassword"
            autocomplete="off"
          ></el-input>
          <span class="warning">*至少6个字符，中英文不限</span>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm', _submitForm)"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { pageList, create, update, del } from '@/api/settingsMenu/accountAccess'
import { adminTypeMap } from '@/config/purchase/admin'
import md5 from 'md5'
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (value.length < 6) {
          callback(new Error('密码至少为6位'))
        }
        if (this.addForm.confirmPassword !== '') {
          this.$refs.addForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'))
      } else if (value !== this.addForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      adminName: null,
      total: 0,
      pageSizeArr: [10, 20, 30, 40],
      pageSize: 10, // 分页页面数量大小
      pageIndex: 1, // 开始页码
      tableData: [],
      adminTypeMap,
      addVisible: false,
      isEdit: false,
      addForm: {
        id: null,
        username: null,
        password: null,
        confirmPassword: null,
      },
      rules: {
        username: [
          { required: true, message: '请输入管理员账户', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' },
        ],
        confirmPassword: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    // 修改table header的背景色
    tableHeaderColor() {
      return 'background-color: #f5f5f5;color: #333;font-weight: bold;text-align:center'
    },
    // 修改table tr行的样式
    tableCellStyle() {
      return 'text-align:center'
    },
    // 分页数量大小设置
    handleSizeChange(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getList()
    },
    // 分页当前页设置
    handleCurrentChange(val) {
      this.pageIndex = val
      this.getList()
    },
    async getList() {
      let param = {
        pageSize: this.pageSize,
        pageIndex: this.pageIndex,
      }
      if (this.adminName) param['username'] = this.adminName
      const loading = this.$loading()
      const { total, list } = await pageList(param)
      loading.close()
      this.total = total
      this.tableData = list
    },
    addUser(row) {
      Object.keys(this.addForm).map(key => (this.addForm[key] = null))
      this.addVisible = true
      if (row) {
        this.isEdit = true
        this.addForm.username = row.username
        this.addForm.id = row.id
      } else this.isEdit = false
    },
    async _submitForm() {
      let param = {
        password: md5(this.addForm.password.toString()),
        confirmPassword: md5(this.addForm.confirmPassword.toString()),
      }
      const loading = this.$loading()
      if (this.isEdit) {
        param['id'] = this.addForm.id
        try {
          await update(param)
          this.$message.success('修改成功')
          this.addVisible = false
          this.getList()
        } catch (error) {
          console.log(error)
        }
      } else {
        param['username'] = this.addForm.username
        try {
          await create(param)
          this.$message.success('新增成功')
          this.addVisible = false
          this.getList()
        } catch (error) {
          console.log(error)
        }
      }
      loading.close()
    },
    async del(id) {
      const loading = this.$loading()
      try {
        await del({ id })
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
      loading.close()
    },
    submitForm(formName, cb) {
      this.$refs[formName].validate(valid => {
        if (!valid) return false
        cb()
      })
    },
  },
  mounted() {
    this.getList()
  },
}
</script>

<style scoped lang="scss">
.warning {
  color: #e30000;
  font-size: 12px;
}
.flex-between {
  display: flex;
  justify-content: space-between;
}
.table-handler {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 5px 15px;
}
</style>